﻿using System;
using System.Text;
using System.Web.Mvc;

namespace Nasa8x.Mvc.Helpers
{
   public static class AntiForgeryExtensions
    {

        // Methods
        public static MvcHtmlString AntiForgeryTokenX(this HtmlHelper helper)
        {
            return AntiForgeryTokenX(helper, null);
        }

        public static MvcHtmlString AntiForgeryTokenX(this HtmlHelper helper, string salt)
        {
            MvcHtmlString _fragment;
            string path = helper.ViewContext.HttpContext.Request.ApplicationPath;
            try
            {
                _fragment = helper.AntiForgeryToken(salt, null, path);
            }
            catch (HttpAntiForgeryException)
            {
                // okay, scrub the cookie and have another go.
                string _cookieName = GetAntiForgeryTokenName(path);
                helper.ViewContext.HttpContext.Request.Cookies.Remove(_cookieName);
                _fragment = helper.AntiForgeryToken(salt, null, path);
            }
            return _fragment;
        }

        #region AntiForgeryData code that shouldn't be sealed
        // Copied from AntiForgeryData since they aren't accessible.
        internal static string GetAntiForgeryTokenName(string appPath)
        {
            if (String.IsNullOrEmpty(appPath))
            {
                return "__RequestVerificationToken";
            }
            else
            {
                return "__RequestVerificationToken_" + Base64EncodeForCookieName(appPath);
            }
        }
        private static string Base64EncodeForCookieName(string s)
        {
            byte[] _rawBytes = Encoding.UTF8.GetBytes(s);
            string _base64String = Convert.ToBase64String(_rawBytes);

            // replace base64-specific characters with characters that are safe for a cookie name
            return _base64String.Replace('+', '.').Replace('/', '-').Replace('=', '_');
        }
        #endregion

    }
}
